package org.jash.shop2202.utils

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder

/**
 * D 是要展示数据的类型
 * layout 参数是展示数据 返回值是 layoutId 和 variableId
 * data 要展示数据列表, 默认为空
 */
class CommonAdapter<D>(val layout:(D) -> Pair<Int, Int>, val data:MutableList<D> = mutableListOf()):Adapter<CommonViewHolder>() {
    /**
     * 以 layoutId 为视图类型
     */
    override fun getItemViewType(position: Int): Int = layout(data[position]).first

    /**
     *
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonViewHolder =
        CommonViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), viewType, parent, false))

    override fun getItemCount(): Int = data.size

    override fun onBindViewHolder(holder: CommonViewHolder, position: Int) {
        val d = data[position]
//        能过 variableId 设置变量
        holder.bing.setVariable(layout(d).second, d)
    }

    /**
     * 运算符重载, 加载数据
     */
    operator fun plusAssign(list: List<D>) {
        val size = data.size
        data += list
        notifyItemRangeInserted(size, list.size)
    }
    fun clear() {
        val size = data.size
        data.clear()
        notifyItemRangeRemoved(0, size)
    }
    fun removeIf(filter:(D) -> Boolean) :Int{
        val index = data.indexOfFirst(filter)
        if (index != -1) {
            data.removeAt(index)
            notifyItemRemoved(index)
        }
        return index
    }
    fun add(index:Int, d:D) {
        data.add(index, d)
        notifyItemInserted(index)
    }
}
class CommonViewHolder(val bing:ViewDataBinding):ViewHolder(bing.root)